from rest_framework.renderers import JSONRenderer
from django.utils import timezone


class StandardJSONRenderer(JSONRenderer):
    """标准JSON响应渲染器 - 自动包装所有响应为统一格式"""

    def render(self, data, accepted_media_type=None, renderer_context=None):
        response = renderer_context.get('response') if renderer_context else None
        if response is None:
            return super().render(data, accepted_media_type, renderer_context)

        # 检查是否已经是统一格式
        if isinstance(data, dict) and 'code' in data and 'message' in data:
            return super().render(data, accepted_media_type, renderer_context)

        # 包装为统一格式
        status_code = response.status_code
        message_map = {
            200: "操作成功", 400: "请求参数错误", 401: "未授权",
            403: "权限不足", 404: "资源不存在", 500: "服务器内部错误"
        }
        message = message_map.get(status_code, "操作完成")

        wrapped_data = {
            'code': status_code, 'message': message, 'data': data,
            'timestamp': timezone.now().isoformat()
        }
        return super().render(wrapped_data, accepted_media_type, renderer_context)
